package com.ruoyi.common.utils.file;

import java.io.*;
import java.net.URLEncoder;
import org.apache.commons.codec.binary.Base64;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


/**
 * 文件处理工具类
 *
 * @author ruoyi
 */
public class FileUtils {
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * @Description :  文件与base64的互相转换操作
     * @Author : mabo
     */
    // filePath 为文件所在全路径: D://file.txt
    public static String file2Str(String filePath) {

        //定义输出流对象
        InputStream in = null;
        byte[] data = null;
        // 读取文件字节数组
        try {
            in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert in != null;
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回 Base64 编码过的字节数组字符串
        assert data != null;
        return encoder.encode(data);
    }

    /**
     * @Description :  文件与base64的互相转换操作
     * @Author : mabo
     */
    // base64FileStr  base字符串
// filePath 同上
    public static boolean str2File(String base64FileStr, String filePath) {

        // 数据为空
        if (base64FileStr == null) {
            return false;
        }
        //判断文件夹是否存在
        File outputFile = new File(filePath);
        File fileP = outputFile.getParentFile();
        if (!fileP.exists() && !fileP.mkdirs() && !fileP.mkdir()) {
            throw new IllegalArgumentException("创建文件目录失败");
        }
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            // Base64解码,对字节数组字符串进行Base64解码并生成文件
            byte[] byt = decoder.decodeBuffer(base64FileStr);
            for (int i = 0, len = byt.length; i < len; ++i) {
                // 调整异常数据
                if (byt[i] < 0) {
                    byt[i] += 256;
                }
            }
            InputStream input = new ByteArrayInputStream(byt);
            // 生成指定格式的文件
            out = new FileOutputStream(filePath);
            byte[] buff = new byte[1024];
            int len;
            while ((len = input.read(buff)) != -1) {
                out.write(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert out != null;
                out.flush();
                out.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public static boolean strToFile(String str, String filePath) throws IOException {
        byte[] bytes = Base64.decodeBase64(str.getBytes());
        FileOutputStream out = new FileOutputStream(filePath);
        out.write(bytes);
        out.flush();
        out.close();
        return  true;
    }
    public static void main(String[] args) throws IOException {

   /*    String a=file2Str("D:\\2222.png");
        str2File(a,"D:\\222.png");*/
        String  a="iVBORw0KGgoAAAANSUhEUgAABpAAAAlJCAYAAACvWiDPAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAP+lSURBVHhe7N0HtGxLVf5tRTKCkkEQAZELKoKCBCWYCMIFyUgSSSpRkqIIgqACEhQELkFAgiRBokQBUYJECWYkSFZBJUrQf3/jWd55v9rFWt2re3fvs88572+MGr1394q1qmZVzbdmrW9YhBBCCCGEEEIIIYQQQgghhNAQASmEEEIIIYQQQgghhBBCCCHsIQJSCCGEEEIIIYQQQgghhBBC2EMEpBBCCCGEEEIIIYQQQgghhLCHCEghhBBCCCGEEEIIIYQQQghhDxGQQgghhBBCCCGEEEIIIYQQwh4iIIUQQgghhBBCCCGEEEIIIYQ9REAKIYQQQgghhBBCCCGEEEIIe4iAFEIIIYQQQgghhBBCCCGEEPYQASmEEEIIIYQQQgghhBBCCCHsIQJSCCGEEEIIIYQQQgghhBBC2EMEpBBCCCGEEEIIIYQQQgghhLCHCEghhBBCCCGEEEIIIYQQQghhDxGQQgghhBBCCCGEEEIIIYQQwh4iIIUQQgghhBBCCCGEEEIIIYQ9REAKIYQQQgghhBBCCCGEEEIIe4iAFEIIIYQQQgghhBBCCCGEEPYQASmEEEIIIYQQQgghhBBCCCHsIQJSCCGEEEIIIYQQQgghhBBC2EMEpBBCCCGEEEII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QQwh4iIIUQQgghhBBCCCGEEEIIIYQ9REAKIYQQQgghhBBCCCGEEEIIe4iAFEIIIYQQQgghhBBCCCGEEPYQASmEEEIIIYQQQgghhBBCCCHsIQJSCCGEEEIIIYQQQgghhBBC2EMEpBBCCCGEEEIIIYQQQgghhLCHCEghhBBCCCGEEEIIIYQQQghhDxGQQgghhBBCCCGEEEIIIYQQwh4iIIUQQggh";

        strToFile(a,"D:\\12.jpg");


    }

    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }

}
